package jehc.djshi.job.publisher;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
/**
 * Netty Server
 */
@Slf4j
@Component
public class NettyServer implements CommandLineRunner {

    /**
     * 线程组用于处理连接工作即主线程组
     */
    private EventLoopGroup bossGroup = new NioEventLoopGroup();

    /**
     * work 线程组用于数据处理
     */
    private EventLoopGroup workGroup = new NioEventLoopGroup();

    @Value("${jehc.djshi.job.host:}")
    private String host;

    @Value("${jehc.djshi.job.port:}")
    private Integer port;

    @Resource
    ChannelUtil channelUtil;

    /**
     *
     */
    public void startServer() {
        InetSocketAddress socketAddress = new InetSocketAddress(host,port);
        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerChannelInitializer(channelUtil))
                .localAddress(socketAddress)
                .option(ChannelOption.SO_BACKLOG, 1024) //设置队列大小
                .childOption(ChannelOption.SO_KEEPALIVE, true); // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
        try { //绑定端口,开始接收进来的连接
            ChannelFuture future = bootstrap.bind(socketAddress).sync();
            log.info("服务器启动开始监听端口: {}", socketAddress.getPort());
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Netty server error",e.getMessage());
        } finally {
            bossGroup.shutdownGracefully(); //关闭主线程组
            workGroup.shutdownGracefully(); //关闭工作线程组
        }
    }

    /**
     *
     * @throws InterruptedException
     */
    @PreDestroy
    public void destory() throws InterruptedException {
        bossGroup.shutdownGracefully().sync();
        workGroup.shutdownGracefully().sync();
        log.info("关闭Netty");
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        new Thread(new NettyServerWorker()).start();
    }

    /**
     *
     */
    class NettyServerWorker implements Runnable{
        public void run(){
            startServer();
        }
    }
}
